
<?php

$g_dal_conns = null;

function dal_mysql_open($params)
{
	$t_conn = mysql_pconnect($params['server'], $params['username'], $params['password']);
	if ($t_conn == false) {
		error_log('mysql error : mysql_pconnect(' . $params['server'] . ', ' . $params['username'] . ', ' . $params['password'] . ')', 0);
		die(0);
	}
	
	if (!mysql_select_db($params['database'])) {
		mysql_close($t_conn);
		die(0);
	}
	
	return $t_conn;
}

function dal_redis_open($params)
{
	$t_conn = new Redis();
	$t_conn->connect($params['host'], $params['port']);
	return $t_conn;
}

function dal_init()
{
	if (!isset($g_dal_conns)) {
		$g_dal_conns = array();
	}
}

function dal_fini()
{
	if (isset($g_dal_conns)) {
		foreach ($g_dal_conns as $key => $conn) {
			$t_params = json_decode($key, true);
			switch ($t_params['provider']) {
				case 'mysql':
					mysql_close($conn);
					break;
				case 'redis':
					$conn->close();
					break;
			}
		}
		$g_dal_conns = null;
	}
}

function dal_getconn($connstr)
{
	if (!isset($g_dal_conns))
		$g_dal_conns = array();
	
	if (isset($g_dal_conns[$connstr]))
		return $g_dal_conns[$connstr];
	
	$t_params = json_decode($connstr, true);
	if ($t_params == null) {
		error_log('error : can\'t decode connstr ' . $connstr, 0);
		die(0);
	}
	
	switch ($t_params['provider']) {
		case 'mysql':
			$t_conn = dal_mysql_open($t_params);
			break;
		case 'redis':
			$t_conn = dal_redis_open($t_params);
			break;
		default:
			error_log('error : provider not found! ' . $connstr, 0);
			die(0);
	}
	
	$g_dal_conns[$connstr] = $t_conn;
	return $t_conn;
}

function dal_mysql_error($conn, $sql, $function)
{
	error_log('mysql error in function ' . $function . '\n\tsql : ' . $sql . '\n\terror: ' . mysql_error($conn), 0);
}

?>
